<?php

namespace App\Http\Models;

use App\Http\Controllers\Controller;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class Task extends Model
{
    /**
     * 获取任务配置列表
     *
     * @return []
     */
    public static function getTaskConfig( $tid=0 )
    {
        if($tid) {
            $get_task = Redis::HGET('TASK_DATA', $tid);
            $tmp = json_decode($get_task, true);
            return $tmp;
        } else {
            $get_all_task = Redis::HGETALL('TASK_DATA');
            // 获取当前所有正常的任务
            $all_tasks = [];
            foreach($get_all_task as $at) {
                $tmp = json_decode($at, true);
                if($tmp['tt'] == 2) continue;
                // 新增需求 去除等级任务改为升级时主动发放
                if($tmp['type'] == config('game.cfg.TaskTypeLvup')) continue;

                $all_tasks[$tmp['id']] = $tmp;
            }
            ksort($all_tasks);
            return $all_tasks;
        }
    }

    /**
     * 获取任务列表
     *
     * @param [type] $uid
     * @return []
     */
    public static function getTaskList( $uid )
    {
        // 获取当前所有正常的任务
        $all_tasks = self::getTaskConfig();

        // 获取用户的任务列表
        $get_my_tasks = DB::table('user_task')->where('uid', $uid)->get();
        $my_tasks = [];
        $today = date('Y-m-d');
        $now = time();
        // $is_update_sign = false;
        foreach($get_my_tasks as $mt) {
            // 不在配置表里的跳过
            if(!isset($all_tasks[$mt['tid']])) continue;
            // 判断隔天重置
            if($all_tasks[$mt['tid']]['daily'] == 1 && date('Y-m-d', $mt['finish']) < $today) {
                // 签到任务特殊处理
                // if($mt['tid'] == config('game.cfg.TaskIDSignIn')) {
                //     $mt['status'] = 1;
                //     $mt['curr']   = 1;
                //     $mt['count']  = 1;
                //     $mt['finish'] = $now;
                    // $is_update_sign = true;
                // } else {
                    $mt['status'] = 0;
                    $mt['curr']   = 0;
                    $mt['count']  = 0;
                    $mt['finish'] = 0;
                    $update_tasks[] = $mt['tid'];
                // }
            }
            $my_tasks[$mt['tid']] = $mt;
        }

        // 重置任务
        if(!empty($update_tasks)) {
            DB::table('user_task')->where('uid', $uid)->whereIn('tid', $update_tasks)->update([
                'status' => config('game.cfg.TaskStatusUncomplete'),
                'curr' => 0,
                'count' => 0,
                'finish' => 0,
            ]);
        }
        // if($is_update_sign) {
        //     DB::table('user_task')->where(['uid'=>$uid, 'tid'=>config('game.cfg.TaskIDSignIn')])->update([
        //         'status' => config('game.cfg.TaskStatusCompleted'),
        //         'curr' => 1,
        //         'count' => 1,
        //         'finish' => $now,
        //     ]);
        // }

        // 判断等级任务
        $min_level_need = 9999;
        $select_tid = null;
        // 第一个餐点任务
        $first_meal = null;
        // 餐点任务列表
        $meal_tasks = [];
        foreach($all_tasks as $tid => $task_conf) {
            // 类型是等级任务
            if($task_conf['type'] == config('game.cfg.TaskTypeLvup')) {
                // 在我的任务中存在且状态不是已完成
                if(isset($my_tasks[$tid]) && $my_tasks[$tid]['status'] == config('game.cfg.TaskStatusReceived')) continue;
                if($task_conf['cond'] < $min_level_need) {
                    $select_tid = $tid;
                    $min_level_need = $task_conf['cond'];
                }
            }
            // 餐点任务
            if($task_conf['type'] == config('game.cfg.TaskTypeMeal')) {
                $meal_tasks[] = $tid;
                if(!$first_meal) $first_meal = $tid;
            }
        }

        // 判断餐点任务
        $has_meal = false;
        $show_meal_tid = [];
        foreach($meal_tasks as $mt) {
            if(\App\Http\Controllers\Controller::nowInTimeRange($all_tasks[$mt]['cond'])) {
                if(!isset($my_tasks[$mt]) || (isset($my_tasks[$mt]) && $my_tasks[$mt]['status'] != config('game.cfg.TaskStatusReceived'))) {
                    $all_tasks[$mt]['status'] = config('game.cfg.TaskStatusCompleted');
                    $show_meal_tid[] = $mt;
                    $has_meal = true;
                    break;
                }
            }
        }

        // 查找最近需要完成的餐点任务
        if($has_meal === false) {
            $last_distance = 1440;
            // $append_meal_task = null;
            foreach ($meal_tasks as $mid) {
                // 跳过今天已完成的餐点任务
                if (isset($my_tasks[$mid]) && $my_tasks[$mid]['status'] == config('game.cfg.TaskStatusReceived')) continue;
                $cond_arr = explode('-', $all_tasks[$mid]['cond']);
                $start_arr = explode(':', $cond_arr[0]);
                $now_arr = [date('H'), date('i')];
                $distance = $start_arr[0] * 60 + $start_arr[1] - $now_arr[0] * 60 - $now_arr[1];
                if ($distance > 0 && $distance < $last_distance) {
                    $last_distance = $distance;
                    $show_meal_tid[] = $mid;
                }
            }
        }
        if(empty($show_meal_tid)) {
            $show_meal_tid[] = $first_meal;
        }

        $uinfo = DB::table('users')->where('id', $uid)->first();
        $show_tasks = [];
        foreach($all_tasks as $tid => $task_conf) {
            // 非当前等级任务 跳过
            if($task_conf['type'] == config('game.cfg.TaskTypeLvup') && $tid != $select_tid) continue;
            // 已完成 并且tomorrow不等于1的 跳过
            if(isset($my_tasks[$tid]) && $my_tasks[$tid]['status'] == config('game.cfg.TaskStatusReceived') && $task_conf['tomorrow'] != 1) continue;
            // 不在餐点任务显示列表的跳过
            if($task_conf['type'] == config('game.cfg.TaskTypeMeal')) {
                if(!in_array($tid, $show_meal_tid)) continue;
            }
            if($tid == 602 && !$uinfo['newUser']) continue;
            // 是否关注社区生活
            if($tid == 500 && (!isset($my_tasks[$tid]) || (isset($my_tasks[$tid]) && $my_tasks[$tid]['status'] != config('game.cfg.TaskStatusReceived')))) {
                $uri = '/supplier-app-api/v1/supplier/lyf/follow';
                $parr = [
                    'lyfuid' => $uinfo['openid'],
                    'type' => 'community',
                ];
                $follow_result = curl_call($uri, $parr);
                if (isset($follow_result['code']) && $follow_result['code'] == 0) {
                    if($follow_result['data']['followStatus'] == 'followed') {
                        if(!isset($my_tasks[$tid])) {
                            $my_tasks[$tid] = [
                                'uid' => $uid,
                                'tid' => $tid,
                                'status' => config('game.cfg.TaskStatusCompleted'),
                                'curr' => 1,
                                'count' => 1,
                            ];
                        }
                        Task::setProgress($uid, 500, 1);
                    }
                }
            }
            // 是否设置过头像
            if($tid == 550 && (!isset($my_tasks[$tid]) || (isset($my_tasks[$tid]) && $my_tasks[$tid]['status'] != config('game.cfg.TaskStatusReceived')))) {
                $uri = '/supplier-app-api/v1/supplier/portrait/updated';
                $parr = [
                    'lyfuid' => $uinfo['openid'],
                ];
                $set_result = curl_call($uri, $parr);
                if (isset($set_result['code']) && $set_result['code'] == 0) {
                    if($set_result['data'] === true) {
                        if(!isset($my_tasks[$tid])) {
                            $my_tasks[$tid] = [
                                'uid' => $uid,
                                'tid' => $tid,
                                'status' => config('game.cfg.TaskStatusCompleted'),
                                'curr' => 1,
                                'count' => 1,
                            ];
                        }
                        Task::setProgress($uid, 550, 1);
                    }
                }
            }

            $task_fodder = 0;
            $rwd = json_decode($task_conf['reward'], true);
            foreach($rwd as $r) {
                if(isset($r['type']) && $r['type'] == 1) {
                    $task_fodder += $r['num'];
                }
            }

            if($task_conf['type'] == config('game.cfg.TaskTypeMeal')) {
                if(!isset($my_tasks[$tid]) || $my_tasks[$tid]['status'] == config('game.cfg.TaskStatusUncomplete')) {
                    if (\App\Http\Controllers\Controller::nowInTimeRange($task_conf['cond'])) {
                        $status = 1;
                        $curr = 1;
                        $count = 1;
                    } else {
                        $status = 0;
                        $curr = 0;
                        $count = 0;
                    }
                } else {
                    $status = 0;
                    $curr = 0;
                    $count = 0;
                }
            } else {
                $status = isset($my_tasks[$tid]) ? $my_tasks[$tid]['status'] : 0;
                $curr   = isset($my_tasks[$tid]) ? $my_tasks[$tid]['curr'] : 0;
                $count  = isset($my_tasks[$tid]) ? $my_tasks[$tid]['count'] : 0;
            }

            $show_tasks[$tid] = [
                'confId'  => $tid,
                'status'  => $status,
                'curr'    => $curr,
                'count'   => $count,
                'fodder'  => $task_fodder,
            ];
        }
        return $show_tasks;
    }

    public static function getLevelTask() {
        $level_tasks = DB::table('game_tasks')->where('type', 3)->get();
        return $level_tasks;
    }

    /**
     * 没用到
     *
     * @param [type] $uid
     * @return void
     */
    public static function getAllNormalTasks($uid) {
        $task_confs = self::getTaskList(1); // 只取tt=1的任务
        $tids = [];
        foreach($task_confs as $tf) {
            $tids[] = $tf['id'];
        }

        $my_tasks = DB::table('tasks')->where(['userId'=>$uid])->whereIn('confId', $tids)->get();

        // 判断是否要重置任务
        $update_ids = [];
        foreach($my_tasks as $mt) {
            if($task_confs[$mt['confId']]['daily'] == 1 && !Controller::sameDay($mt['validTime'])) {
                $update_id[] = $mt['id'];
            }
        }
        // 刷新任务
        $today_zero = Controller::todayZero();
        DB::table('tasks')->whereIn('id', $update_ids)->update([
            'status' => config('game.cfg.TaskStatusUncomplete'),
            'curr' => 0,
            'count' => 0,
            'validTime' => $today_zero,
        ]);

        $show_tasks = [];
        $meal_tasks = [];

        $uinfo = DB::table('users')->where('id', $uid)->first();

        $task_maps = [];
        foreach($my_tasks as $mt) {
            $task_maps[$mt['confId']] = $mt;
        }
        foreach($tids as $tid) {
            $t_cfg = $task_confs[$tid];
            if(!isset($task_maps[$tid])) {
                $task_maps[$tid] = [
                    'id' => $tid,
                    'confId' => $tid,
                    'status' => config('game.cfg.TaskStatusUncomplete'),
                    'curr' => 0,
                    'count' => 0,
                    'validTime' => 0,
                    'tomorrow' => $t_cfg['tomorrow'],
                ];
            } else {
                $task_maps[$tid]['tomorrow'] = $t_cfg['tomorrow'];
            }
            switch($t_cfg['type']) {
                case config('game.cfg.TaskTypeNormal'):
                    if($task_maps[$tid]['status'] == config('game.cfg.TaskStatusUncomplete') || $task_maps[$tid]['status'] == config('game.cfg.TaskStatusCompleted')) {
                        // 关注生活频道检查
                        if($tid == 500 && $task_maps[$tid]['status'] != config('game.cfg.TaskStatusReceived')) {
                            $uri = '/supplier-app-api/v1/supplier/lyf/follow';
                            $parr = [
                                'lyfuid' => $uinfo['openid'],
                                'type' => 'community',
                            ];
                            $follow_result = curl_call($uri, $parr);
                            if (isset($follow_result['code']) && $follow_result['code'] == 0) {
                                if($follow_result['data']['followStatus'] == 'followed') {
                                    self::setProgress($uid, 500, 1);
                                    $task_maps[$tid]['status'] = config('game.cfg.TaskStatusCompleted');
                                    $task_maps[$tid]['curr'] = 1;
                                    $task_maps[$tid]['count'] = 1;
                                }
                            }
                        }
                        // 个人头像设置
                        if($tid == 550 && $task_maps[$tid]['status'] != config('game.cfg.TaskStatusReceived')) {
                            $uri = '/supplier-app-api/v1/supplier/portrait/updated';
                            $parr = [
                                'lyfuid' => $uinfo['openid'],
                            ];
                            $follow_result = curl_call($uri, $parr);
                            if (isset($follow_result['code']) && $follow_result['code'] == 0) {
                                if($follow_result['data'] === true) {
                                    self::setProgress($uid, 500, 1);
                                    $task_maps[$tid]['status'] = config('game.cfg.TaskStatusCompleted');
                                    $task_maps[$tid]['curr'] = 1;
                                    $task_maps[$tid]['count'] = 1;
                                }
                            }
                        }
                        $show_tasks[] = $task_maps[$tid];
                    } else {
                        if($task_maps[$tid]['tomorrow'] == 1) {
                            $show_tasks[] = $task_maps[$tid];
                        }
                    }
                    break;
                case config('game.cfg.TaskTypeMeal'):
                    $meal_tasks[] = $task_maps[$tid];
                    break;
                case config('game.cfg.TaskTypeBrowse'):
                    #if($task_maps[$tid]['status'] == config('game.cfg.TaskStatusUncomplete') || $task_maps[$tid]['status'] == config('game.cfg.TaskStatusCompleted')) {
                        $show_tasks[] = $task_maps[$tid];
                    #}
                    break;
            }
        }

        // 判断餐点任务
        $has_meal = false;
        foreach($meal_tasks as $k => $mt) {
            if(\App\Http\Controllers\Controller::nowInTimeRange($task_confs[$mt['id']]['cond']) && $mt['status'] != config('game.cfg.TaskStatusReceived')) {
                $meal_tasks[$k]['status'] = config('game.cfg.TaskStatusCompleted');
                $show_tasks[] = $mt;
                $has_meal = true;
                break;
            }
        }

        // 查找最近需要完成的餐点任务
        if(!$has_meal) {
            $last_distance = 1440;
            $append_task = null;
            foreach($meal_tasks as $mt) {
                if($mt['status'] == config('game.cfg.TaskStatusReceived')) continue;
                $cond_arr = explode('-', $task_confs[$mt['id']]['cond']);
                $start_arr = explode(':', $cond_arr[0]);
                $now_arr = [date('H'), date('i')];
                $distance = $start_arr[0]*60 + $start_arr[1] - $now_arr[0]*60 - $now_arr[1];
                if($distance > 0 && $distance < $last_distance) {
                    $last_distance = $distance;
                    $append_task = $mt;
                }
            }
            if($append_task) {
                $show_tasks[] = $append_task;
            }
        }

        // 取最近一个等级任务
        $lv_tasks = self::getLevelTask();
        $min_level_need = 99999;
        $select_t = null;
        foreach($lv_tasks as $lt) {
            if(isset($task_maps[$lt['id']])) {
                if($task_maps[$lt['id']]['status'] == config('game.cfg.TaskStatusReceived')) continue;
                $tdata = $task_maps[$lt['id']];
            } else {
                $tdata = [
                    'type' => 3,
                    'confId' => $lt['id'],
                    'curr' => 0,
                    'count' => 0,
                    'name' => $lt['name'],
                    'desc' => $lt['desc'],
                    'iconUrl' => $lt['iconUrl'],
                    'jump' => $lt['jump'],
                    'target' => $lt['target'],
                    'cond' => $lt['cond'],
                ];
            }
            if($lt['cond'] < $min_level_need) {
                $select_t = $tdata;
                $min_level_need = $lt['cond'];
            }
        }
        $show_tasks[] = $select_t;

        return $show_tasks;
    }

    /**
     * 设置任务状态为完成
     *
     * @param [type] $uid
     * @param [type] $task_id
     * @param [type] $progress
     * @return void
     */
    public static function setProgress($uid, $task_id, int $progress)
    {
        $now = time();
        if ($task_id == 0) {
            $level_tasks = self::getLevelTask();
            $check_tids = [];
            foreach($level_tasks as $lt) {
                if($progress >= $lt['cond']) {
                    $check_tids[] = $lt['id'];
                }
            }
            $get_undone_level_tasks = DB::table('user_task')->where('uid', $uid)->whereIn('tid', $check_tids)->get();
            if(!empty($get_undone_level_tasks)) {
                foreach($get_undone_level_tasks as $undone_t) {
                    if(in_array($undone_t['tid'], $check_tids)) {
                        foreach($check_tids as $k => $v) {
                            if($v == $undone_t['tid']) {
                                unset($check_tids[$k]);
                            }
                        }
                    }
                }
            }
            // 增加任务红点
            Redis::SET('TaskReddot:'.$uid, 1);
            foreach($check_tids as $tid) {
                DB::table('user_task')->insert([
                    'uid' => $uid,
                    'tid' => $tid,
                    'status' => config('game.cfg.TaskStatusCompleted'),
                    'curr' => 1,
                    'count' => 1,
                    'finish' => $now,
                ]);
            }
        } else {

            $task_cfg = self::getTaskConfig( $task_id );
            if (empty($task_cfg)) return false;

            $task_data = DB::table('user_task')->where(['uid' => $uid, 'tid' => $task_id])->first();
            if (!isset($task_data['uid'])) {
                $task_data = [
                    'uid' => $uid,
                    'tid' => $task_id,
                    'status' => config('game.cfg.TaskStatusUncomplete'),
                    'curr' => 0,
                    'count' => 0,
                    'finish' => $now,
                ];
                $tid = DB::table('user_task')->insert($task_data);
                if (!$tid) return false;
            }

            // 普通任务和浏览任务
            if ($task_cfg['type'] == config('game.cfg.TaskTypeNormal') || $task_cfg['type'] == config('game.cfg.TaskTypeBrowse')) {
                if($task_id == '601') {
                    if ($progress == 1) {
                        if ($task_data['status'] == config('game.cfg.TaskStatusUncomplete') || date('Y-m-d', $task_data['finish']) < date('Y-m-d')) {
                            $task_data['status'] = 1;
                            $task_data['curr'] = 1;
                            $task_data['count'] = 1;
                            $task_data['finish'] = $now;
                            DB::table('user_task')->where(['uid' => $uid, 'tid' => $task_id])->update([
                                'status' => $task_data['status'],
                                'curr' => $task_data['curr'],
                                'count' => $task_data['count'],
                                'finish' => $task_data['finish'],
                            ]);
                        }
                    }
                } else if($task_id == '2017') {
                    if($progress == 1  && $task_data['status'] == config('game.cfg.TaskStatusUncomplete')) {
                        $task_data['status'] = 1;
                        $task_data['curr'] = 1;
                        $task_data['count'] = 1;
                        $task_data['finish'] = $now;
                        DB::table('user_task')->where(['uid' => $uid, 'tid' => $task_id])->update([
                            'status' => $task_data['status'],
                            'curr' => $task_data['curr'],
                            'count' => $task_data['count'],
                        ]);
                    }
                } else {
                    // 隔日重置
                    $today = date('Y-m-d');
                    if($task_cfg['tomorrow'] == 1 && date('Y-m-d', $task_data['finish']) < $today) {
                        $task_data['status'] = 0;
                        $task_data['curr'] = 0;
                        $task_data['count'] = 0;
                        $task_data['finish'] = 0;
                    }
                    if ($task_data['status'] != config('game.cfg.TaskStatusUncomplete') || $task_data['count'] >= $task_cfg['count']) {
                        return true;
                    }
                    $task_data['curr'] += $progress;
                    if ($task_data['curr'] >= $task_cfg['target']) {
                        $task_data['curr'] = $task_cfg['target'];
                        $task_data['count']++;
                        $task_data['status'] = config('game.cfg.TaskStatusCompleted');
                        $task_data['finish'] = $now;
                        // 增加任务红点
                        Redis::SET('TaskReddot:'.$uid, 1);
                    }
                    if ($task_data['count'] >= $task_cfg['count']) {
                        $task_data['count'] = $task_cfg['count'];
                    }
                    if(intval($task_id) === 1) {
                        $task_data['finish'] = $now;
                    }
                    DB::table('user_task')->where(['uid' => $uid, 'tid' => $task_id])->update([
                        'status' => $task_data['status'],
                        'curr' => $task_data['curr'],
                        'count' => $task_data['count'],
                        'finish' => $task_data['finish'],
                    ]);
                }
            }

            return true;
        }

    }

    /**
     * 检查任务红点是否还存在
     *
     * @param [type] $uid
     * @return bool
     */
    public static function checkReddot( $uid ) {
        $list = self::getTaskList( $uid );
        $reddot = false;
        if( !empty( $list ) ) {
            foreach ($list as $info ) {
                // var_dump($info);
                if($info['status'] == config('game.cfg.TaskStatusCompleted')) {
                    $reddot = true;
                    break;
                }
                if($info['confId'] == config('game.cfg.TaskIDSignIn') && $info['status'] == config('game.cfg.TaskStatusUncomplete')) {
                    $reddot = true;
                    break;
                }
            }
        }
        if($reddot) {
            // 任务红点
            Redis::SET('TaskReddot:'.$uid, 1);
        } else {
            // 删除任务红点
            Redis::DEL('TaskReddot:'.$uid);
        }
        return $reddot;
    }

    /**
     * 获取等级奖励
     */
    public static function getLevelReward($level) {
        $get_all_task = Redis::HGETALL('TASK_DATA');
        // 获取当前所有正常的任务
        $all_tasks = [];
        foreach($get_all_task as $at) {
            $tmp = json_decode($at, true);
            if($tmp['type'] == config('game.cfg.TaskTypeLvup') && $tmp['cond'] >= $level) {
                $all_tasks[$tmp['cond']] = $tmp;
            }
        }
        // var_dump($all_tasks);
        $select = [];
        if(!empty($all_tasks)) {
            ksort($all_tasks);
            $select = array_shift($all_tasks);
            if(isset($select['reward'])) {
                $select['reward'] = json_decode($select['reward'], true);
            }
        }
        return $select;
    }
}
